import { Entity, System, World } from '@ecs/index'
import { createStart } from '../entities'
import { Position, Size } from '../components'

/**
 * 碰撞系统（AABB法）
 * @description 计算小鸟和障碍物之间的碰撞
 */
export class CollisionSystem extends System {
  constructor() {
    super()
  }

  public update(world: World): void {
    const brid = world.findNameWithEntities('brid')[0]
    const floor = world.findNameWithEntities('floor')[0]
    const upObstacles = world.findNameWithEntities('upObstacle')
    const downObstacles = world.findNameWithEntities('downObstacle')

    if (!brid || !floor || !upObstacles.length || !downObstacles.length) {
      return
    }

    const bridComponentMap = world.findEntityWithComponents(brid)
    const bridPosition = bridComponentMap.get(Position)
    const bridSize = bridComponentMap.get(Size)

    // 小鸟边框模型
    const birdBorder = {
      top: bridPosition.y,
      left: bridPosition.x,
      right: bridPosition.x + bridSize.w,
      bottom: bridPosition.y + bridSize.h
    }

    const floorComponentMap = world.findEntityWithComponents(floor)
    const floorPosition = floorComponentMap.get(Position)
    const floorSize = floorComponentMap.get(Size)

    // 地板边框模型
    const floorBorder = {
      top: floorPosition.y,
      left: floorPosition.x,
      right: floorPosition.x + floorSize.w,
      bottom: floorPosition.y + floorSize.h
    }

    let isCollision = false

    // 1.地板碰撞
    if (birdBorder.bottom >= floorBorder.top) {
      isCollision = true
    }

    // 2.障碍物碰撞
    const checkObstacle = (isUpObstacle: boolean) => {
      return function (item: Entity) {
        const obstacleComponentMap = world.findEntityWithComponents(item)
        const obstaclePosition = obstacleComponentMap.get(Position)
        const obstacleSize = obstacleComponentMap.get(Size)

        // 障碍物边框模型
        const obstacleBorder = {
          top: obstaclePosition.y,
          left: obstaclePosition.x,
          right: obstaclePosition.x + obstacleSize.w,
          bottom: obstaclePosition.y + obstacleSize.h
        }

        // 鸟 进入 障碍物区域
        if (
          birdBorder.right >= obstacleBorder.left &&
          birdBorder.left <= obstacleBorder.right
        ) {
          if (isUpObstacle === true) {
            // 1.上障碍物碰撞
            if (birdBorder.top <= obstacleBorder.bottom) {
              isCollision = true
              return false
            }
          } else {
            // 2.下障碍物碰撞
            if (birdBorder.bottom >= obstacleBorder.top) {
              isCollision = true
              return false
            }
          }
        }
        return true
      }
    }
    upObstacles.every(checkObstacle(true))
    downObstacles.every(checkObstacle(false))

    // 3.撞击结束游戏
    if (isCollision) {
      world.data.isGameOver = true
      world.pause()
      createStart(world)
    }
  }

  public destory(): void {}
}
